package com.ultisense.gassensor;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.EditText;


public class MainActivity extends AppCompatActivity implements ParameterDialogFragment.ParameterDialogListener{

    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    //private TextView mTextMessage;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment selectedFragment = null;
            FragmentManager manager = getSupportFragmentManager();
            if (item.getItemId()==R.id.navigation_home) {
                FragmentTransaction transaction = manager.beginTransaction();
                if (manager.findFragmentByTag("BtFragment") == null){
                    selectedFragment = new BtFragment();
                    transaction.replace(R.id.content, selectedFragment,"BtFragment");
                }
                else{
                    selectedFragment = manager.findFragmentByTag("BtFragment");
                    transaction.replace(R.id.content, selectedFragment);
                }

                transaction.addToBackStack(null);
                transaction.commit();
            }

            else if(item.getItemId()==R.id.navigation_charts) {
                FragmentTransaction transaction = manager.beginTransaction();
                if (manager.findFragmentByTag("ChartsFragment") == null) {
                    selectedFragment = new ChartsFragment();
                    transaction.replace(R.id.content, selectedFragment,"ChartsFragment");
                }
                else{
                    selectedFragment = manager.findFragmentByTag("ChartsFragment");
                    transaction.replace(R.id.content, selectedFragment);
                }
                transaction.addToBackStack(null);
                transaction.commit();
            }

            else if(item.getItemId()==R.id.navigation_share) {
                FragmentTransaction transaction = manager.beginTransaction();
                if (manager.findFragmentByTag("ShareFragment") == null) {
                    selectedFragment = new ShareFragment();
                    transaction.replace(R.id.content, selectedFragment,"ShareFragment");
                }
                else{
                    selectedFragment = manager.findFragmentByTag("ShareFragment");
                    transaction.replace(R.id.content, selectedFragment);
                }
                transaction.addToBackStack(null);
                transaction.commit();
            }

            return true;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android M Permission check
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},PERMISSION_REQUEST_COARSE_LOCATION);
            }
        }
        if (findViewById(R.id.content) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }
            // Create an instance of BtActivity
            BtFragment BtFrag = new BtFragment();

            // In case this activity was started with special instructions from an Intent,
            // pass the Intent's extras to the fragment as arguments
            BtFrag.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.content, BtFrag, "BtFragment").commit();
            showParameterDialog();
        }

        //mTextMessage = (TextView) findViewById(R.id.message);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

    public void showParameterDialog() {
        // Create an instance of the dialog fragment and show it
        DialogFragment dialog = new ParameterDialogFragment();
        dialog.show(getSupportFragmentManager(), "ParameterDialogFragment");
    }

    // The dialog fragment receives a reference to this Activity through the
    // Fragment.onAttach() callback, which it uses to call the following methods
    // defined by the ParameterDialogFragment.ParameterDialogListener interface

    public void onDialogPositiveClick(DialogFragment dialog) {
        // User touched the dialog's positive button
        BtFragment btfrag = (BtFragment) getSupportFragmentManager().findFragmentById(R.id.content);
        EditText sensornum = (EditText) dialog.getDialog().findViewById(R.id.sensornum);
        EditText basesignal = (EditText) dialog.getDialog().findViewById(R.id.basesignal);
        EditText maxlevel = (EditText) dialog.getDialog().findViewById(R.id.maxlevel);
        EditText criticallevel = (EditText) dialog.getDialog().findViewById(R.id.criticallevel);
        if(btfrag!=null){
            if(!sensornum.getText().toString().isEmpty())
                btfrag.setSensorNum(Integer.parseInt(sensornum.getText().toString()));

            if(!basesignal.getText().toString().isEmpty())
                btfrag.setBaseSignal(Float.parseFloat(basesignal.getText().toString()));

            if(!maxlevel.getText().toString().isEmpty())
                btfrag.setMaxLevel(Float.parseFloat(maxlevel.getText().toString()));

            if(!criticallevel.getText().toString().isEmpty())
                btfrag.setCriticalLevel(Float.parseFloat(criticallevel.getText().toString()));

            btfrag.initGraph();
        }
    }

    public void onDialogNegativeClick(DialogFragment dialog) {
        // User touched the dialog's positive button
        BtFragment btfrag = (BtFragment) getSupportFragmentManager().findFragmentById(R.id.content);
        if(btfrag!=null)
            btfrag.initGraph();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_COARSE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // TODO request success
                }
                break;
        }
    }
}
